package dbinit;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import core.attribute.model.Attribute;
import core.attribute.model.AttributeSet;
import core.util.HibernateCoreUtil;

public class InitAttributeSet 
{
	public static AttributeSet getAttributeSetByName(String name)
	{
		AttributeSet as = null ;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			as = (AttributeSet) session.createCriteria(AttributeSet.class).add(Restrictions.eq("name", name)).uniqueResult();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return as ;
	}
	public static AttributeSet getAttributeSetByUuid(Long uuid)
	{
		AttributeSet as = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				as = (AttributeSet) session.get(AttributeSet.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return as ;
	}
	public static List<AttributeSet> listAll()
	{
		List<AttributeSet> asLst = new ArrayList<AttributeSet>() ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				asLst = (List<AttributeSet> ) session.createQuery("from AttributeSet").list();
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return asLst ;
	}
	public static Long doinit(String name , Set<Attribute> attributes)
	{
		AttributeSet as = getAttributeSetByName(name) ;
		Long uuid = null;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			if(as == null)
			{
				as = new AttributeSet();
			    as.setName(name);
			    as.setEnabled(true);
			    as.setAttributes(attributes);
			    uuid = (Long) session.save(as);
			}
			else
			{
				as.setAttributes(attributes);
				 as.setEnabled(true);
				session.merge(as);
				uuid = as.getUuid();  
			}
			
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		
		return uuid ;
	}
}
